//
//  OMFMDBCartHelper.m
//  OMENGO_NEW
//
//  Created by 梁尚嘉 on 2017/4/27.
//  Copyright © 2017年 Kamfat. All rights reserved.
//

#import "OMFMDBCartHelper.h"
#import "OMProduct.h"
#import "OMCartProduct.h"
#import <FMDB.h>
#import "MainConfigure.h"
@implementation OMFMDBCartHelper

+ (NSMutableDictionary *)parameterWithProduct:(id<OMProductProtocol>)product reverseCartkey:(NSString **)cartKey_
{
    NSString *cartKey = KTSystemStorageSingleton.cartKey;
    NSString *productId ;
    if ([product isKindOfClass:[OMProduct class]]) {
        productId = product.id;
    }else {
        OMCartProduct *cartProduct = (id)product;
        productId = cartProduct.productId;
    }
    NSMutableDictionary *parameters = [@{
                                         @"productId":productId,
                                         @"quantity":[@(product.quantity)stringValue]} mutableCopy
                                       ];
    !cartKey.length?:[parameters setObject:cartKey forKey:@"cartKey"];
    *cartKey_ = cartKey;
    return parameters;
}

+ (void)itemAddition:(OMProduct *)product
 withButtonAnimation:(UIButton*)button
          targetView:(UIView*)targetView
{
    NSString *cartKey;
    NSMutableDictionary *parameters = [self parameterWithProduct:product reverseCartkey:&cartKey];
    [parameters setObject:@"1" forKey:@"quantity"];
    [KTHttpUtils POST:@"cart/add.jhtml"
           parameters:parameters
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {

               if (isSuccess) {
                   if (responseObject[OMDatumKey][OMCartKey]) {
                       KTSystemStorageSingleton.cartKey = responseObject[OMDatumKey][OMCartKey];
                   }
                   [OMFakeAction cartAnimationAddWithButton:button toTargetView:targetView];
               }else {
                   [OMHUD HUDError:message?:@"添加失败"];
               }
    }];
}



+ (NSString *)DBAddress
{
    return [NSHomeDirectory() stringByAppendingString:@"/Documents/OMENGO.db"];
}

+ (FMDatabaseQueue *)FMDBQueue
{
    return [[FMDatabaseQueue alloc]initWithPath:self.DBAddress];
}

+ (NSString *)cartTableName
{
    return @"TEMP_CART_TABLE";
}

+ (BOOL)checkCartTable:(FMDatabase *)dataBase
{
    NSString *SQL = [NSString stringWithFormat:
                     @"CREATE TABLE IF NOT EXISTS %@ ("
                     "name text NOT NULL,"
                     "id text NOT NULL,"
                     "price text NOT NULL,"
                     "image text NOT NULL,"
                     "unit text NOT NULL,"
                     "weight text NOT NULL,"
                     "brand text NOT NULL,"
                     "quantity integer)"
                     ,self.cartTableName];
    @try {
        return [dataBase executeUpdate:SQL];
    } @catch (NSException *exception) {
        NSLog(@"%@",exception.debugDescription);
        return false;
    } @finally {

    }
}


+ (void)updateCartTable:(OMProduct *)product
            withHandler:(void (^)(BOOL success))handler
{
    [self.FMDBQueue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        @try {
            //数据存在
            FMResultSet *result = [db executeQuery:[NSString stringWithFormat:@"SELECT COUNT(*) FROM %@ WHERE id='%@'",self.cartTableName,product.id]];
            BOOL isExist = [result boolForColumnIndex:0];
            NSString *SQL = @"";
            if (isExist) {

                if (product.quantity) {
                    SQL = [NSString stringWithFormat:
                           @"UPDATE %@ SET quantity=%lu WHERE id='%@'",
                           self.cartTableName,
                           (unsigned long)product.quantity,
                           product.id];
                }else {
                    SQL = [NSString stringWithFormat:@"DELETE FROM %@ WHERE id='%@'",
                           self.cartTableName,
                           product.id];
                }
            }else {

                SQL = [NSString stringWithFormat:
                       @"INSERT INTO %@ VALUES ("
                       "'%@',"
                       "'%@',"
                       "'%@',"
                       "'%@',"
                       "'%@',"
                       "'%@',"
                       "'%@',"
                       "%lu)"
                       ,self.cartTableName,
                       product.name,
                       product.id,
                       product.price,
                       product.image,
                       product.unit,
                       product.weight,
                       product.brand,
                       (unsigned long)product.quantity];
            }
            //更新购物车
            handler([db executeUpdate:SQL]);

        } @catch (NSException *exception) {
            handler(false);
        } @finally {
            
        }
    }];
}
@end
